package com.foreverwin.mes.lims.controller;

import com.foreverwin.mes.common.enums.HandleEnum;
import com.foreverwin.mes.core.base.FrontPage;
import com.foreverwin.mes.core.base.AjaxResult;
import com.foreverwin.mes.core.utils.CommonMethods;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.foreverwin.mes.core.utils.StringUtils;
import com.foreverwin.mes.lims.model.RetentionSample;
import com.foreverwin.mes.lims.service.RetentionSampleService;
import com.foreverwin.mes.lims.util.NowString;
import com.foreverwin.mes.meapi.model.Resrce;
import com.foreverwin.mes.meapi.service.ResrceService;
import com.foreverwin.mes.production.dto.SfcInWorkDto;
import com.foreverwin.mes.production.service.SfcExService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 *
 * @author Mark
 * @since 2020-03-04
 */
@Controller
@RequestMapping("/retentionSamples")
public class RetentionSampleController {
    private final Logger logger = LoggerFactory.getLogger(RetentionSampleController.class);
    private final Boolean isLocalTest = false; //是否在本地测试（若为true，返回自定义数据）

    @Autowired
    public RetentionSampleService retentionSampleService;

    @Autowired
    public ResrceService resrceService;

    @Autowired
    private SfcExService sfcExService;

    /**
    * 根据id查询
    *
    * @param id 主键
    * @return
    */
    @ResponseBody
    @GetMapping("/{id:.+}")
    public AjaxResult getRetentionSampleById(@PathVariable String id) {
        RetentionSample result;
        try {
            result = retentionSampleService.selectById(id);
        } catch (Exception e) {
            logger.error("getRetentionSampleById -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(result);
    }

    /**
     * 查询所有数据
     *
     * @return
     */
    @ResponseBody
    @GetMapping("")
    public AjaxResult getRetentionSampleList(RetentionSample retentionSample){
        List<RetentionSample> result;
        try {
            EntityWrapper<RetentionSample> EntityWrapper = new EntityWrapper<>();
            EntityWrapper.setEntity(retentionSample);
            result = retentionSampleService.selectList(EntityWrapper);
        } catch (Exception e) {
            logger.error("getRetentionSampleList -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(result);
    }

    /**
     * 分页查询数据
     *
     * @param frontPage  分页信息
     * @return
     */
    @ResponseBody
    @GetMapping("/getRetentionSamplePageList")
    public AjaxResult getRetentionSamplePageList(FrontPage<RetentionSample> frontPage, RetentionSample retentionSample){
        Page result;
        try {
            String site = CommonMethods.getSite();
            retentionSample.setSite(site);
            EntityWrapper<RetentionSample> EntityWrapper = new EntityWrapper<>();
            EntityWrapper.setEntity(retentionSample);
            if (frontPage.getGlobalQuery() != null && !"".equals(frontPage.getGlobalQuery().trim())) {
                //TODO modify global query
                EntityWrapper
                    .like("handle", frontPage.getGlobalQuery())
                    .or().like("site", frontPage.getGlobalQuery())
                    .or().like("resource", frontPage.getGlobalQuery())
                    .or().like("resoDesc", frontPage.getGlobalQuery())
                    .or().like("retenSampBatch", frontPage.getGlobalQuery())
                    .or().like("item", frontPage.getGlobalQuery())
                    .or().like("itemName", frontPage.getGlobalQuery())
                    .or().like("measUnit", frontPage.getGlobalQuery())
                    .or().like("creator", frontPage.getGlobalQuery())
                    .or().like("updater", frontPage.getGlobalQuery())
        ;
            }
            result = retentionSampleService.selectPage(frontPage.getPagePlus(), EntityWrapper);
        } catch (Exception e) {
            logger.error("getRetentionSamplePageList -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(result);
    }

    /**
     * 保存和修改公用
     * @param retentionSample  传递的实体
     * @return  null 失败  实体成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/_save")
    public AjaxResult retentionSampleSave(@RequestBody RetentionSample retentionSample) {
        String site = CommonMethods.getSite();
        String user = CommonMethods.getUser();
        Date nowTime = new Date();
        //------------------本地测试数据开始------------------------------------------------------------------------------------
        if(isLocalTest) {
            user = "mark";
        }
        //------------------------------------------------------------------------------------------------------------
        String handle = StringUtils.createQUID();
        retentionSample.setHandle(handle);
        retentionSample.setSite(site);
        retentionSample.setCreator(user);
        retentionSample.setUpdater(user);
        retentionSample.setCreatedDateTime(nowTime);
        retentionSample.setModifiedDateTime(nowTime);
        int count;
        try {
            count = retentionSampleService.insert(retentionSample) ? 1 : 0;
        } catch (Exception e) {
            logger.error("retentionSampleSave -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(count == 0 ? null : retentionSample);
    }

    /**
     * 根据id删除对象
     * @param id  实体ID
     * @return 0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.DELETE, value = "/{id:.+}")
    public AjaxResult retentionSampleDelete(@PathVariable("id") String id){
        int count;
        try {
            count = retentionSampleService.deleteById(id) ? 1 : 0;
        } catch (Exception e) {
            logger.error("retentionSampleDelete -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success("count: " + count);
    }

    /**
     * 批量删除对象
     * @param ids 实体集合ID
     * @return  0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/_batchDelete")
    public AjaxResult removeByIds(List<String> ids){
        int count;
        try {
            count = retentionSampleService.deleteBatchIds(ids) ? 1 : 0;
        } catch (Exception e) {
            logger.error("retentionSampleBatchDelete -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success("count: " + count);
    }

    /**
     * 查询：设备编号、设备描述
     *
     * @return
     */
    @ResponseBody
    @GetMapping("/getResource")
    public AjaxResult getResource(RetentionSample retentionSample){
        ArrayList<RetentionSample> result = new ArrayList<RetentionSample>();
        Resrce resrce = new Resrce();
        resrce.setSite(CommonMethods.getSite());
        List<Resrce> resrce_l = resrceService.selectList(resrce);

        for(int i=0;i<resrce_l.size();i++){
            RetentionSample ins = new RetentionSample();
            Resrce resrce_ins = resrce_l.get(i);

            ins.setResource(resrce_ins.getResrce());
            ins.setResoDesc(resrce_ins.getDescription());

            result.add(ins);
        }

        return AjaxResult.success(result);
    }

    /**
     * 查询：留样批次、物料编号、物料名称、单位
     *
     * @return
     */
    @ResponseBody
    @GetMapping("/getRetentionSampleBatch")
    public AjaxResult getRetentionSampleBatch(RetentionSample retentionSample){
        String site = CommonMethods.getSite();
        List<RetentionSample> result = retentionSampleService.selectInventoryBatch(retentionSample);
        return AjaxResult.success(result);
    }
}